<?php
namespace app\admin\controller\sum\store;

use addons\sum\library\pay\PayService;
use addons\sum\service\pay\PayOper;
use addons\sum\service\store\Agent as StroeService;
use addons\sum\service\Wallet as WalletService;
use app\admin\model\sum\Pay;
use app\admin\model\sum\user\User as UserModel;
use think\Db;
use think\exception\HttpResponseException;
use addons\sum\exception\SumException;
use app\admin\model\sum\StockOrder as StockOrderModel;
use app\admin\model\sum\goods\Goods as GoodsModel;
use app\admin\model\sum\store\Goods as StoreGoodsModel;

/**
 * 商户进货管理
 */
class StockOrder extends \app\admin\controller\sum\Common
{

    public function _initialize()
    {
        \app\admin\controller\sum\Common::_initialize();
        $this->model = new StockOrderModel;
    }


    /**
     * 商户进货列表
     */
    public function index()
    {
        $store_id = $this->request->param('store_id');
        if(!$store_id){
            $this->error('参数错误');
        }
        if (!$this->auth->isSuperAdmin()) {
            $admin=$this->auth->getUserInfo();
            if($admin['store_id']!=$store_id){
                $this->error('你不能操作该商户进货订单');
            }
        }

        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $records = $this->model->sheepFilter()->with(['goods','store','express'])->paginate($this->request->param('list_rows', 10));
        $this->success('获取成功', null, $records);
    }
    /**
     * 添加
     */
    public function add()
    {
        $store_id = $this->request->param('store_id');
        if(!$store_id){
            $this->error('参数错误');
        }
        if (!$this->auth->isSuperAdmin()) {
            $admin=$this->auth->getUserInfo();
            if($admin['store_id']!=$store_id){
                $this->error('你不能操作该商户进货订单');
            }
        }
        $goods_id = $this->request->param('goods_id');
        if(!$goods_id){
            $this->error('进货商品参数错误');
        }
        $goods=GoodsModel::where('id',$goods_id)->find();

        $store_goods=StoreGoodsModel::where('goods_id',$goods['id'])->where('store_id',$store_id)->find();


        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $params = $this->request->only(['store_id','goods_id','type', 'goods_num','consignee', 'mobile', 'province_name','province_id', 'city_name', 'city_id', 'district_name', 'district_id', 'address']);

        $this->svalidate($params, '.add');

        $params['order_sn']=get_sn($store_id,'SO');
        //进货价格每个店铺不一样
        $params['stock_price']=$store_goods['stock_price'];
        $params['goods_amount']=$params['stock_price']*$params['goods_num'];
        $params['dispatch_amount']=0;
        $params['status']='unpaid';//未支付
        $params['order_amount']=$params['goods_amount']+$params['dispatch_amount'];//订单总价额
        $params['pay_fee']=$params['order_amount'];//需支付金额
        $params['remain_pay_fee']=$params['order_amount'];//需支付金额
        $this->model->save($params);

        $this->success('保存成功', null, $this->model);
    }

    /**
     * 详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $detail = $this->model->where('id', $id)->find();
        if (!$detail) {
            $this->error(__('No Results were found'));
        }
        $detail['dian']=json_decode($detail['dian'],true);
        $this->success('获取成功', null, $detail);
    }

    /**
     * 支付
     * @param $id
     * @return string|void
     * @throws \think\Exception
     *
     */
    public function pay($id = null)
    {

        $detail = $this->model->where('id', $id)->find();
        if (!$detail) {
            $this->error(__('No Results were found'));
        }
        if($detail['status']!='unpaid'){
            $this->error('该进货单不能支付');
        }
        $payment='wechat';
        $order_type='stock_order';//进货订单支付
        // pay 实例
        $payOper = new PayOper(null,$detail['store_id']);
        // 微信（第三方）付款
        $payModel = $payOper->wechat($detail, $detail['pay_fee'], $order_type);

        $order_data = [
            'order_id' => $detail->id,
            'out_trade_no' => $payModel->pay_sn,
            'total_amount' => $payModel->pay_fee,      // 剩余支付金额
            'description' => '进货订单支付',      //
        ];
        $payService = new PayService($payment,"H5");
        try {
            $result = $payService->pay($order_data);
        } catch (\Yansongda\Pay\Exception\Exception $e) {
            $this->error('支付失败' . (config('app_debug') ? "：" . $e->getMessage() : '，请重试'));
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();

            $this->error('支付失败' . (config('app_debug') ? "：" . $message : '，请重试'));
        }
        $this->view->assign('order_data', $order_data);
        $this->view->assign('pay_data', $result);
        return $this->view->fetch();
    }


    /**
     * 编辑(支持批量)
     */
    public function edit($id = null)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch('add');
        }

        $params = $this->request->only(['image', 'store_name','user_name', 'phone', 'dian','status']);

        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list, $params) {
            $count = 0;
            foreach ($list as $item) {
                $params['id'] = $item->id;
                if(isset($params['dian'])&&is_array($params['dian'])){
                    $params['dian']=json_encode($params['dian']);
                }
                $this->svalidate($params);
                $count += $item->save($params);
            }
            return $count;
        });

        if ($result) {
            $this->success('更新成功', null, $result);
        } else {
            $this->error('更新失败，未改变任何记录');
        }
    }

    /**
     * 删除(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
                $count += $item->delete();
            }
            return $count;
        });

        if ($result) {
            $this->success('删除成功', null, $result);
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 评价回收站
     *
     * @return void
     */
    public function recyclebin()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $comments = $this->model->onlyTrashed()->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $comments);
    }


    /**
     * 还原(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function restore($id = null)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }
        $items = $this->model->onlyTrashed()->where('id', 'in', $id)->select();
        Db::transaction(function () use ($items) {
            $count = 0;
            foreach ($items as $item) {
                $count += $item->restore();
            }

            return $count;
        });

        $this->success('还原成功');
    }


    /**
     * 销毁(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function destroy($id = null)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }
        if ($id !== 'all') {
            $items = $this->model->onlyTrashed()->whereIn('id', $id)->select();
        } else {
            $items = $this->model->onlyTrashed()->select();
        }
        $result = Db::transaction(function () use ($items) {
            $count = 0;
            foreach ($items as $comment) {
                $count += $comment->delete(true);
            }
            return $count;
        });

        if ($result) {
            $this->success('销毁成功', null, $result);
        }
        $this->error('销毁失败');
    }

    /**
     * 确认收货
     *
     * @param  $id
     * @return \think\Response
     */
    public function complete($id)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
                $params['id'] = $item->id;
                $params['status']='completed';
                $count += $item->save($params);
                //增加库存
                StoreGoodsModel::where('store_id',$item->store_id)->where('goods_id',$item->goods_id)->setInc('stock',$item->goods_num);

                //结算代理商业绩
                //先获取商户信息
                $store=\app\admin\model\sum\store\Store::where('id',$item['store_id'])->find();
                if($store){
                    $agent_user=UserModel::where('id',$store['agent_id'])->find();
                    if($agent_user){
                        WalletService::change($agent_user, 'commission', $item['pay_fee'], 'reward_income', '来自店铺:'.$store['store_name'].'的代理业绩');
                    }
                }
            }
            return $count;
        });

        if ($result) {
            $this->success('操作成功', null, $result);
        } else {
            $this->error(__('操作失败，未改变任何记录'));
        }
    }



}
